package com.lucky.common.config;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 可以在连接上携带区域信息
 */
@Component
public class AppLocaleResolver implements org.springframework.web.servlet.LocaleResolver {

	Locale myLocal = Locale.CHINA;

	/**
	 * 通过cookie存储区域语言信息
	 */
	@Override
	public Locale resolveLocale(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies(); // 获取cookie数组
		String lang = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 遍历cookie数组
                if ("ClientLanguage".equals(cookie.getName())) {
                    lang = cookie.getValue();
                    break;
                }
            }
        }
//		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		if (StringUtils.hasText(lang)) {
            switch (lang) {
                case "zh" -> myLocal = Locale.CHINA;
                case "en" -> myLocal = Locale.US;
                case "ja" -> myLocal = Locale.JAPAN;
            }
		}
		return myLocal;
	}

	@Override
	public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

	}
}